package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.RandomStringUtils;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 通用工具类
 */
public class CommonUtils {

    public static void main(String[] args) throws Exception {
//        System.out.println(new Sha256Hash("admin", "YzcmCZNvbXocrsz9dm8e").toHex());
//        FileUtils.createImage("嘻嘻", "/home/imbybFile/headImg.png");
//        String path = "/app/user/getUserInfo";
//        System.out.println(path.indexOf("/app/"));
        String url = "http://49.4.8.33:9000/cnpc-mcq-hse-dev/MCQHSE/supervision/find/2023/04/12/1c6e75ad-6ad3-4f49-b23c-962dc96d0ee3.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=admin%2F20230412%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20230412T015656Z&X-Amz-Expires=518400&X-Amz-SignedHeaders=host&X-Amz-Signature=eee4d19a32c823dcb785cd98caf0099164adec9f46d0ca0fabe90239d8b3e290";
        url = URLEncoder.encode(url, "utf-8");

        System.out.println(url);
    }

    /**
     * 判断手机格式是否正确
     *
     * @param phone
     * @return
     */
    public static JSONObject isPhone(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        JSONObject ret = new JSONObject();
        if (StringUtils.isBlank(phone)) {
            ret.put("errCode", -1);
            ret.put("errMsg", "手机号不能为空");
            return ret;
        }
        if (phone.length() != 11) {
            ret.put("errCode", -1);
            ret.put("errMsg", "手机号应为11位数");
            return ret;
        }
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(phone);
        boolean isMatch = m.matches();
        if (!isMatch) {
            ret.put("errCode", -1);
            ret.put("errMsg", "请填入正确的手机号");
            return ret;
        }
        ret.put("errCode", 0);
        return ret;
    }

    /**
     * 返回特殊格式月数据，[{day: '1',whether: 'false',weekday:'周一'}]，需补全当月头尾不完整的周信息
     * 通过下月1号，查看周几，若为周日，不操作；若不为周日，补到周六
     * 然后-1从当月最后1天补充数据到1号
     * 通过上月信息补全月初周信息
     * 周日到周六为1到7
     *
     * @param year  查询年份
     * @param month 查询月份
     */
    public static JSONArray getMonth(Integer year, Integer month) {
        Map<Integer, String> weekMap = new HashedMap<>();
        weekMap.put(1, "周日");
        weekMap.put(2, "周一");
        weekMap.put(3, "周二");
        weekMap.put(4, "周三");
        weekMap.put(5, "周四");
        weekMap.put(6, "周五");
        weekMap.put(7, "周六");
        JSONArray dateArray = new JSONArray();
        JSONObject timeObj;

        Calendar last_cal = Calendar.getInstance();
        Calendar cal = Calendar.getInstance();
        Calendar next_cal = Calendar.getInstance();
        //下个月
        next_cal.set(year, month, 1);
        if (next_cal.get(Calendar.DAY_OF_WEEK) != 1) {
            for (int i = next_cal.get(Calendar.DAY_OF_WEEK); i <= 7; i++) {
                timeObj = new JSONObject();
                timeObj.put("day", "");
                timeObj.put("whether", "false");
                timeObj.put("weekday", weekMap.get(i));
                dateArray.add(timeObj);
            }
        }
        //本月
        cal.set(year, month, 1);
        cal.add(cal.DATE, -1);
        for (int i = cal.get(Calendar.DAY_OF_MONTH); i >= 1; i--) {
            timeObj = new JSONObject();
            timeObj.put("day", cal.get(Calendar.DAY_OF_MONTH) + "");
            timeObj.put("whether", "true");
            timeObj.put("weekday", weekMap.get(cal.get(Calendar.DAY_OF_WEEK)));
            dateArray.add(0, timeObj);

            cal.add(cal.DATE, -1);
        }
        //上个月
        last_cal.set(year, month - 1, 1);
        last_cal.add(last_cal.DATE, -1);
        if (last_cal.get(Calendar.DAY_OF_WEEK) != 7) {
            for (int i = last_cal.get(Calendar.DAY_OF_WEEK); i >= 1; i--) {
                timeObj = new JSONObject();
                timeObj.put("day", "");
                timeObj.put("whether", "false");
                timeObj.put("weekday", weekMap.get(i));
                dateArray.add(0, timeObj);
            }
        }
        return dateArray;
    }

    /**
     * 按长度获取随机数
     *
     * @param length
     * @return
     */
    public static String getRandom(Integer length) {
        String result = "";
        Random rand = new Random();
        int n = 20;
        if (null != length && length > 0) {
            n = length;
        }
        for (int i = 0; i < n; i++) {
            int randInt = rand.nextInt(9) + 1;

            result += randInt;
        }
        return result;
    }

    public static String get8LengthId(int type) {
        Random random = new Random();
        int num;
        // 0：用户自己注册生成id范围：10000001~89999999
        // 1：后台导入用户生成id范围：90000000~99999998
        if (type == 0) num = random.nextInt(79999999) + 10000001;
        else num = random.nextInt(9999999) + 90000000;
        return num + "";
    }

    /**
     * 昵称编码保存
     *
     * @param nickname
     * @return
     */
    public static String encodeNickname(String nickname) {
        try {
            //进行编码
            nickname = Base64.encodeBase64String(nickname.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nickname;
    }

    /**
     * 昵称解码
     *
     * @param nickname
     * @return
     */
    public static String decodeNickname(String nickname) {
        try {
            //进行解码
            nickname = new String(Base64.decodeBase64(nickname), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nickname;
    }

    /**
     * 判断是否为奇数
     *
     * @param sumValue
     * @return
     */
    public static boolean isOdd(int sumValue) {
        if ((sumValue & 1) == 1) {
            return true;
        }
        return false;
    }

    /**
     * 生成随机昵称
     *
     * @return
     */
    public static String createRandName() {
        String filename = "uid_" + RandomStringUtils.randomAlphanumeric(10);
        return filename;
    }

    /**
     * 生成随机中文
     *
     * @return
     */
    public static String getRandomChineseName(int count) {
        String name = "";
        if (count > 0) {
            for (int i = 0; i < count; i++) {
                name += (char) (0x4e00 + (int) (Math.random() * (0x9fa5 - 0x4e00 + 1))) + "";
            }
        }
        return name;
    }

    /**
     * 获取下一天日期
     *
     * @param nowDateStr
     * @return
     */
    public static String getNextDate(String nowDateStr) {
        Date nowDate = com.ruoyi.common.utils.DateUtil.stringToDate(nowDateStr, "yyyyMMdd");
        Date nextDate = com.ruoyi.common.utils.DateUtil.addDateDays(nowDate, 1);
        return DateUtil.format(nextDate, "yyyyMMdd");
    }

    public static BigDecimal getRandomMoney(BigDecimal total, int count) {
        int totalVal = (int) (total.doubleValue() * 100); // 随机生成整数，将钱数化为整数

        Integer val;
        // 当前剩余钱数 满足0.01每人时
        if (count != 0 && totalVal / count == 1) {
            val = 1;
            count--;
            return BigDecimal.valueOf(val.longValue()).divide(BigDecimal.valueOf(100l));
        }

        if (count <= 0) {
            val = 0;
        } else if (count == 1) {
            val = totalVal;
        } else {
            int temp; //剩下的金额
            while (true) {
                // 随机生成当前金额的随机数 [0,totalVal/count),尽量平均一点
                val = new Random().nextInt(totalVal / count);
                temp = totalVal - val;
                // 判断生成的金额大于0，且剩余的钱数够剩下人平分到0.01元
                if (temp / (count - 1) >= 1 && val > 0) {
                    BigDecimal temp1 = BigDecimal.valueOf(val.longValue()).divide(BigDecimal.valueOf(100l));
                    BigDecimal temp2 = new BigDecimal(temp + "").divide(BigDecimal.valueOf(100l));
                    BigDecimal tempSum = temp1.add(temp2);
                    break;
                }
            }
        }
        return BigDecimal.valueOf(val.longValue()).divide(BigDecimal.valueOf(100l));
    }

    public static boolean judgeAccountContainsOther(String str) {
        // 不能纯数字
        char[] c = str.toCharArray();
        int digitalNums = 0;
        for (int i = 0; i < str.length(); i++) {
            if (c[i] >= '0' && c[i] <= '9') {
                digitalNums++;
            }
        }
        if (digitalNums == str.length()) return true;

        // 只能包含字母和数字
        int charNums = 0;
        for (int i = 0; i < str.length(); i++) {
            if (c[i] >= 'a' && c[i] <= 'z' || c[i] >= 'A' && c[i] <= 'Z' || c[i] >= '0' && c[i] <= '9') {
                charNums++;
            }
        }
        if (charNums < str.length()) return true;

        return false;
    }

    /**
     * 判断是否为整数
     *
     * @param str
     * @return
     */
    public static boolean isNumber(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

}